package com.computer.network.security.filter;

import com.computer.network.po.SysUser;
import com.computer.network.service.SysUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 登录后权限认证
 * 通过用户是否有角色判断
 *
 * @Author cgs
 * @Date 2022/9/9 16:04
 */
@Component
public class MenuAccessDecisionManager implements AccessDecisionManager {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        SysUser principal = (SysUser) authentication.getPrincipal();
        if (principal == null) {
            throw new BadCredentialsException("用户未登录");
        }
        for (ConfigAttribute configAttribute : collection) {
            String attribute = configAttribute.getAttribute();
            List<Long> longList = (List<Long>) ((SysUser) authentication.getPrincipal()).getRoleId();
            if (longList != null) {
                Iterator<Long> iterator = longList.iterator();
                while (iterator.hasNext()) {
                    //有相同id则匹配成功
                    if (attribute.indexOf(String.valueOf(iterator.next())) == 0) {
                        return;
                    }
                }
            }
        }
        throw new AccessDeniedException("SimpleGrantedAuthority!!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
